function Users()
{
	var labbyContainer = $("#labby");
	this.initInfoPopup = function(response)
	{
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		//Close function
		$(".more-info-popup .close-btn").on("click", function(){
			$(html).remove();
		});
	};
	this.saveUser = function(user, afterSaveFx)
	{
		debugger;
		var filters = util.filters();
		util.appendFilter({val: user.name, name: "Nombre", filters: [filters.MAX_SIZE, filters.NAME], extraval: 250});
		util.appendFilter({val: user.first_lastname, name: "Primer apellido", filters: [filters.MAX_SIZE, filters.LETTERS_ONLY], extraval: 250});
		util.appendFilter({val: user.second_lastname, name: "Segundo apellido", filters: [filters.MAX_SIZE, filters.LETTERS_ONLY], extraval: 250});
		util.appendFilter({val: user.id, name: "Id", filters: [filters.MAX_SIZE], extraval: 250});
		util.appendFilter({val: user.id, name: "Id", filters: [filters.MIN_SIZE], extraval: 7});
		util.appendFilter({val: user.date_of_birth, name: "Fecha de nacimiento", filters: [filters.IS_ADULT]});
		util.appendFilter({val: user.address, name: "Dirección", filters: [filters.MAX_SIZE], extraval: 250});
		util.appendFilter({val: user.email, name: "Email", filters: [filters.MAX_SIZE, filters.EMAIL], extraval: 250});
		util.appendFilter({val: user.phone, name: "Teléfono", filters: [filters.MAX_SIZE, filters.NUMBERS_ONLY], extraval: 250});
		
		var onSuccessFx = function()
		{
			var params = {
				user: user
			};
			var afterSave = function(response)
			{
				response = JSON.parse(response);
				if(util.handleResponseError(response))
				{
					return;
				}
				if(afterSaveFx)
				{
					afterSaveFx();
				}
			};
			$.post("users/saveUser", params, afterSave);
		};
		var result = util.runFilters(onSuccessFx);

	};
	this.deleteUser = function(user, afterDeleteFx)
	{
		debugger;	
		var params = {
			user: user
		};
		var afterDelete = function(response)
		{
			response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			if(afterDeleteFx)
			{
				afterDeleteFx();
			}
		};
		$.post("users/deleteUser", params, afterDelete);
	};
	this.initEditPopup = function(response)
	{
		var thisObj = this;
		response.user = JSON.parse(response.user);
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		var addOnChangeEvent = function(el, attr)
		{
			$(el).on("change", function(){
				response.user[attr] = $(this).val();
			});
			$(el).removeAttr("id");
		};
		//Form elements
		addOnChangeEvent($("#id"),"id");
		addOnChangeEvent($("#name"),"name");
		addOnChangeEvent($("#first_lastname"),"first_lastname");
		addOnChangeEvent($("#second_lastname"),"second_lastname");
		addOnChangeEvent($("#date_of_birth"),"date_of_birth");
		addOnChangeEvent($("#address"),"address");
		addOnChangeEvent($("#email"),"email");
		addOnChangeEvent($("#phone"),"phone");

		$(".edit-popup .save-btn").on("click", function(){
			var afterSave = function()
			{
				alert("El usuario fue guardado con éxito");
				util.refresh("/users");
			};
			thisObj.saveUser(response.user, function(){afterSave();});
		});
		//Close function
		$(".edit-popup .cancel-btn").on("click", function(){
			if(confirm("¿Está seguro?"))
			$(html).remove();
		});
	};
	this.initCreatePopup = function(response)
	{
		var thisObj = this;
		response.user = JSON.parse(response.user);

		response.user.id = "";
		response.user.name = "";
		response.user.first_lastname = "";
		response.user.second_lastname = "";
		response.user.date_of_birth = "";
		response.user.address = "";
		response.user.email  ="";
		response.user.phone = "";

		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		var addOnChangeEvent = function(el, attr)
		{
			$(el).on("change", function(){
				response.user[attr] = $(this).val().trim();
			});
			$(el).removeAttr("id");
		};
		//Form elements
		addOnChangeEvent($("#id"),"id");
		addOnChangeEvent($("#name"),"name");
		addOnChangeEvent($("#first_lastname"),"first_lastname");
		addOnChangeEvent($("#second_lastname"),"second_lastname");
		addOnChangeEvent($("#date_of_birth"),"date_of_birth");
		addOnChangeEvent($("#address"),"address");
		addOnChangeEvent($("#email"),"email");
		addOnChangeEvent($("#phone"),"phone");

		$(".create-popup .save-btn").on("click", function(){
			var afterSave = function()
			{
				alert("El usuario fue guardado con éxito");
				util.refresh("/users");
			};
			thisObj.saveUser(response.user, function(){afterSave();});
		});
		//Close function
		$(".create-popup .cancel-btn").on("click", function(){
			if(confirm("¿Está seguro?"))
			$(html).remove();
		});
	};
	this.showMoreInfo = function(id)
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			debugger;
			response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			thisObj.initInfoPopup(response);
		};
		var params = 
		{
			pk: id
		}
		$.post("users/getUserInfo", params, afterLoad);
	};
	this.showEditUser = function(id)
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			debugger;
			var responseObject = JSON.parse(response);
			if(responseObject.error)
			{
				alert(responseObject.message);
				return;
			}
			
			thisObj.initEditPopup(responseObject);
		};
		var params = 
		{
			pk: id
		}
		$.post("users/getUserEdit", params, afterLoad);
	};
	this.showDeleteUser = function(id)
	{	
		if(confirm("¿Realmente quieres borrar este usuario?"))
		{
			var afterDeleteFx = function()
			{
				alert("El usuario fue eliminado con éxito.");
				util.refresh("/users");
			};
			this.deleteUser(id, afterDeleteFx);
		}
	};
	this.showCreateUser = function()
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			thisObj.initCreatePopup(response);
		};
		$.post('users/createUser', {}, afterLoad);
	};

	this.regenerateUserPassword = function(id)
	{
		debugger;
		var afterRegenerateFx = function(response)
		{
			response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			alert("Se ha generado el password de este usuario exitosamente.");
		};
		var params = {
			pk: id
		};
		$.post("users/regeneratePassword", params, afterRegenerateFx);
	};
	this.initUsersFilters = function()
	{
		var nameEl = $(".users-filter .name input");
		var firstLastnameEl = $(".users-filter .first-lastname input");
		var secondLastnameEl = $(".users-filter .second-lastname input");
		var emailEl = $(".users-filter .email input");
		var phoneEl = $(".users-filter .phone input");

		var name = $(nameEl).val();
		var firstLastname = $(firstLastnameEl).val();
		var secondLastname = $(secondLastnameEl).val();
		var email = $(emailEl).val();
		var phone = $(phoneEl).val();

		nameEl.on("change", function(){
			name = $(this).val().trim();
		});

		firstLastnameEl.on("change", function(){
			firstLastname = $(this).val().trim();
		});

		secondLastnameEl.on("change", function(){
			secondLastname = $(this).val().trim();
		});

		emailEl.on("change", function(){
			email = $(this).val().trim();
		});

		phoneEl.on("change", function(){
			phone = $(this).val().trim();
		});

		$(".users-filter .controls a").on("click", function(){
			var filters = util.filters();
			var searchEmailPattern = /(^[a-zA-Z]+$)|(^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)/;
			util.appendFilter({val: name, name: "Nombre", filters: [filters.MAX_SIZE, filters.NAME], extraval: 250, canBeEmpty: true});
			util.appendFilter({val: firstLastname, name: "Primer apellido", filters: [filters.MAX_SIZE, filters.LETTERS_ONLY], extraval: 250, canBeEmpty: true});
			util.appendFilter({val: secondLastname, name: "Segundo apellido", filters: [filters.MAX_SIZE, filters.LETTERS_ONLY], extraval: 250, canBeEmpty: true});
			util.appendFilter({val: email, name: "Email", filters: [filters.MAX_SIZE], extraval: 250, canBeEmpty: true});
			util.appendFilter({val: email, name: "Email", filters: [filters.MATCH_PATTERN], message: "Escriba un valor válido para el campo email, ya sea una palabra contenida en el email o el email en sí", extraval: searchEmailPattern, canBeEmpty: true});
			util.appendFilter({val: phone, name: "Teléfono", filters: [filters.MAX_SIZE, filters.NUMBERS_ONLY], extraval: 250, canBeEmpty: true});
			var afterFilterFx = function()
			{
				var url = "users";
				url = name === "" ? url : util.addUrlParam(url, "name", name);
				url = firstLastname === "" ? url : util.addUrlParam(url, "firstLastname", firstLastname);
				url = secondLastname === "" ? url : util.addUrlParam(url, "secondLastname", secondLastname);
				url = email === "" ? url : util.addUrlParam(url, "email", email);
				url = phone === "" ? url : util.addUrlParam(url, "phone", phone);
				util.goTo(url);
			};

			util.runFilters(afterFilterFx);
			
		});
	};
	this.restoreUser = function(id)
	{
		if(confirm("¿Seguro que desea restaurar este usuario?"))
		{
			var params = {
				id: id
			};
			var afterRestoreFx = function(response)
			{
				response = JSON.parse(response);
				if(util.handleResponseError(response))
				{
					return;
				}
				alert("El usuario fue restaurado con éxito.");
				util.refresh("/users");
			};
			$.post("users/restoreUser", params, afterRestoreFx);
		}
	}
	this.init = function()
	{
		var thisObj = this;
		$("#users-table tr").each(function()
		{
			var theTr = this;
			var id = $(theTr).attr("id");
			var moreBtn = $(theTr).find("a[class='btn more']");
			var editBtn = $(theTr).find("a[class='btn edit']");
			var deleteBtn = $(theTr).find("a[class='btn delete']");
			var regeneratePasswordBtn = $(theTr).find("a[class='btn pw-reset']");

			moreBtn.on("click", function()
			{
				thisObj.showMoreInfo(id);
			});
			editBtn.on("click", function()
			{
				thisObj.showEditUser(id);
			});
			deleteBtn.on("click", function()
			{
				thisObj.showDeleteUser(id);
			});
			regeneratePasswordBtn.on("click", function(){
				thisObj.regenerateUserPassword(id);
			});
			$(theTr).removeAttr("id");
		});

		$("#users-trash-table tr").each(function()
		{
			var theTr = this;
			var id = $(theTr).attr("id");
			var moreBtn = $(theTr).find("a[class='btn more']");
			var restoreBtn = $(theTr).find("a[class='btn restore']");

			moreBtn.on("click", function()
			{
				thisObj.showMoreInfo(id);
			});
			restoreBtn.on("click", function(){
				thisObj.restoreUser(id);
			});
			$(theTr).removeAttr("id");
		});
		
		$(".user-options .create").on("click", function(){
			thisObj.showCreateUser();
		});
	};
	this.init();
	this.initUsersFilters();
}

var usr = new Users();